from django.shortcuts import render
from cookie import models
from django.shortcuts import redirect


# from django.contrib.auth.models import User
# from django.contrib import auth
# Create your views here.

def login(request):
    if request.method == "GET":
        return render(request, "cookie/login.html")
    username = request.POST.get("username")
    password = request.POST.get("pwd")
    user_obj = models.UserInfo.objects.filter(username=username, password=password).first()
    print(user_obj)
    if not user_obj:
        return redirect('/cookie/login/')
    else:
        rep = redirect("/cookie/index/")
        rep.set_cookie("is_login", True)
        return rep


def index(request):
    print(request.COOKIES.get('is_login'))
    status = request.COOKIES.get('is_login')  # 收到浏览器的再次请求，判断浏览器携带的cookie是不是登录成功的时候相应的cookie
    if not status:
        return redirect('/cookie/login/')
    return render(request, 'cookie/index.html')


def logout(request):
    rep = redirect('/cookie/login/')
    rep.delete_cookie("is_login")
    return rep  # 点击注销后执行删除cookie，不再保存用户状态，并弹到登录页面


def order(request):
    print(request.COOKIES.get('is_login'))
    status = request.COOKIES.get('is_login')
    if not status:
        return redirect('/cookie/login/')
    return render(request, "cookie/order.html")


def s_login(request):
    if request.method == "GET":
        return render(request, 'cookie/login.html')
    username = request.POST.get("username")
    password = request.POST.get("pwd")
    use_obj = models.UserInfo.objects.filter(username=username, password=password).first()
    # print(username.username)
    print(use_obj)
    if not use_obj:
        return redirect("/cookie/s_login/")
    else:
        request.session['is_login'] = True
        request.session['user1'] = username
        return redirect("/cookie/s_index/")


def s_index(request):
    status = request.session.get('is_login')
    if not status:
        return redirect('/cookie/s_login/')
    return render(request, "cookie/s_index.html")


def s_logout(request):
    # del request.session["is_login"]  # 删除session_data 里的一组键值对
    request.session.flush()  # 删除一条记录包括（session_key session_data expire_date）三个字段
    return redirect('/cookie/s_login/')
